<template>
  <div>
    <el-card>
      <!--主页视图区域-->
      <!--图片区域-->
      <div class="block" v-if="!(checkout === 0 || checkout === 1)">
        <div class="condition">
          <div class="text1">{{type === 'add' ? '手动报废' : '报废修改'}}</div>
        </div>
        <div class="bg-card">
          <el-form :inline="true" :model="topForm" ref="topForm" :rules="topFormRule">
            <el-row>
              <el-form-item
                prop="value1"
                label="报废单号"
                v-if="type !== 'add'"
              >
                <el-input
                  v-model="scarpNum"
                  disabled
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item prop="value2" label="仓库">
                <el-input value="备品备件仓库" disabled></el-input>
              </el-form-item>
              <el-form-item label="报废申请时间">
                <el-date-picker
                  v-model="scarpFillTime"
                  type="date"
                  format="yyyyMMdd"
                  value-format="yyyyMMdd"
                  :picker-options="pickerOptions"
                  :disabled="type === 'edit' || isDisabled"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="scarpType" label="报废类型" v-if="type !== 'view'">
                <el-select v-model="topForm.scarpType" :value="1">
                  <el-option
                    v-for="item in scarpTypeOpt"
                    :key="item.index"
                    :label="item.value"
                    :value="item.index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row v-if="type !== 'view'">
              <el-form-item prop="goodsId01" label="货品编号">
                <el-input
                  v-model="topForm.goodsId01"
                  style="width:100px"
                ></el-input>
                <el-card style="width:200px" class="item" v-show="topForm.goodsId01 && isShow">
                  <div v-for="(item, index) in newlist" :key="index" @click="handleSearch(item)" @mouseover="mouseOver(index)" @mouseleave="mouseLeave(index)" :style="index === active ? 'background-color: #F5F9FE' : ''">
                    {{item}}
                  </div>
                </el-card>
              </el-form-item>
              <el-form-item prop="goodsName" label="货品名称">
                <el-input
                  v-model="topForm.goodsName"
                  style="width:100px"
                ></el-input>
              </el-form-item>
              <el-form-item prop="specification" label="型号规格">
                <el-input v-model="topForm.specification"></el-input>
              </el-form-item>
              <el-form-item prop="goodsUnit" label="单位">
                <el-input
                  v-model="topForm.goodsUnit"
                  style="width:80px"
                ></el-input>
              </el-form-item>
              <el-form-item prop="scarpGoodsNumber" label="数量">
                <el-input
                  v-model="topForm.scarpGoodsNumber"
                  style="width:80px"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row v-if="type !== 'view'" style="display:flex;align-items: center;">
              <el-form-item prop="scarpx" label="报废原因">
                <el-input v-model="topForm.scarpx" type="textarea" style="width:200px;margin-top:30px"></el-input>
              </el-form-item>
              <el-form-item prop="scarpRemarks" label="备注">
                <el-input v-model="topForm.scarpRemarks" type="textarea" style="width:200px;margin-top:30px"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" style="margin-top:28px" @click="handleTopSubmit">新增货品</el-button
                >
              </el-form-item>
            </el-row>
          </el-form>
        </div>
      </div>
      <br />
      <div v-if="type === 'add' ">
        <div class="condition" style="margin-top:30px" v-if="type !== 'view'">
          <div class="title">批量报废</div>
        </div>
        <div class="bg-card" v-if="type !== 'view'">
          <el-form :inline="true" :model="midForm" ref="midForm">
            <el-form-item>
              <el-upload
                class="upload-demo"
                action="/api/restful/v1/dd/inbound/uploadEvaluateExcel"
                :data="{scarpFillTime}"
                :on-success="handleUploadSuccess"
                ref="upload"
                :headers="headers"
              >
                <el-button style="margin-top:28px" type="primary">上传报废单模板<i class="el-icon-upload el-icon--right"></i></el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleEvaluationExcel" style="margin-top:28px">批量报废</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="downloadTemplate" style="margin-left:50px;margin-top:28px">下载报废单模板</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
        <div class="condition" style="margin-top:30px">
          <div class="title">报废单货品展示</div>
        </div>
        <div class="bg-card" v-if="type !== 'view'">
          <el-button type="danger" @click="handleDel" style="margin-left:30px">删除</el-button>
          <el-button  style="margin-left:30px" @click="handleSubmit(0)">保存报废单</el-button>
          <el-button type="primary" style="margin-left:30px" @click="handleSubmit(1)">提交</el-button>
          <el-button type="info" @click="handleReturn" style="margin-left:30px">返回</el-button>
        </div>
        <br />
        <div>
          <el-table
          :data="newlist1"
          border
          style="width: 100%"
          ref="table"
          @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" v-if="type !== 'view'"></el-table-column>
            <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
            <el-table-column prop="goodsId01" label="货品编号" align="center"></el-table-column>
            <el-table-column prop="goodsName" label="货品名称" align="center"></el-table-column>
            <el-table-column prop="specification" label="型号规格" align="center"></el-table-column>
            <el-table-column label="报废类型" align="center">
              <template slot-scope="{row}">
                <span>{{ row.scarpType === 1 ? '库内报废' : '库外报废'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsUnit" label="单位" align="center"></el-table-column>
            <el-table-column prop="scarpGoodsNumber" label="数量" align="center"></el-table-column>
            <el-table-column prop="scarpx" label="报废原因" align="center"></el-table-column>
            <el-table-column prop="scarpRemakes" label="备注" align="center"></el-table-column>
          </el-table>
          <el-button v-if="checkout === 0 " type="primary" @click="handleReturn" style="margin:30px 0 0 30px">返回</el-button>
          <div class="block" style="float:right;margin-bottom:10px">
            <span class="demonstration"></span>
            <el-pagination
              :current-page.sync="page"
              :page-size="10"
              layout="total, prev, pager, next"
              :total="total"
            ></el-pagination>
          </div>
        </div>
          <div class="bg-card" v-if="checkout" style="margin-top:20px">
            <div style="margin-top:20px">
              <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="请输入审核意见"
                  v-model="textarea">
              </el-input>
            </div>
            <el-button type="success" @click="handleCheckout(1)" style="margin-left:30px;margin-top:30px">同意</el-button>
            <el-button type="info" @click="handleCheckout(2)" style="margin-left:30px">退回</el-button>
            <el-button @click="handleReturn" style="margin-left:30px">返回</el-button>
          </div>
    </el-card>
  </div>
</template>
<script>
import FileSaver from "file-saver";
export default {
  data() {
    return {
      isDisabled: false,
      headers: {
        Authorization: sessionStorage.getItem("User_Code")
      },
      page: 1,
      total: 0,
      topFormRule: {
        goodsId01: [{ required: true, message: "必填项", trigger: "blur" }],
        goodsName: [{ required: true, message: "必填项", trigger: "blur" }],
        specification: [{ required: true, message: "必填项", trigger: "blur" }],
        goodsUnit: [{ required: true, message: "必填项", trigger: "blur" }],
        scarpGoodsNumber: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        scarpType: [{ required: true, message: "必填项", trigger: "change" }],
        scarpx: [{ required: true, message: "必填项", trigger: "blur" }]
      },
      query: {
        currentPage: 0,
        num: '',
        pageSize: 0
      },
      query1: {
        day: "",
        goodsId01: "",
        // inboundTime: "",
        month: "",
        warehouse: 2,
        year: ""
      },
      initTopForm: {
        goodsId01: "",
        goodsName: "",
        scarpGoodsNumber: "",
        goodsUnit: "",
        scarpX: "",
        scarpRemarks: "",
        specification: "",
        scarpType: 1,
        warehouse: 2,
        waringValue: 0,
      },
      uploadFile: {
        url: "",
      },
      topForm: {},
      midForm: {},
      type: "add",
      scarpFillTime: "",
      scarpTypeOpt: [{ index: 1, value: "库内报废" }, { index: 2, value: "库外报废" }],
      tableData: [],
      selectData: [],
      scarpRemarks: "",
      scarpx: "",
      wareHouse: 2,
      textarea: '',
      checkout: null,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      active: null,
      isShow: false,
      idArr: [],
      activeIdArr: [],
    };
  },
  methods: {
    handleTopSubmit() {
      if (!this.scarpFillTime) {
        return this.$message.info("请填写报废时间");
      }
      this.$refs.topForm.validate((valid) => {
        if (valid) {
          console.log(this.topForm)
          this.tableData.push(
            Object.assign({ id: this.tableData.length }, this.topForm)
          );
          this.$refs.topForm.resetFields();
          this.$refs.table.toggleRowSelection(
            this.tableData[this.tableData.length - 1]
          );
          this.isDisabled = true
        }
      });
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    handleUploadSuccess(res) {
      if (res.code == 1) {
        this.$message.success(res.message);
        this.uploadFile.url = res.object;
      } else {
        this.$message.error(res.message);
      }
    },
    async handleEvaluationExcel () {
      if (this.uploadFile.url) {
        try {
          console.log(1)
          const res = await this.$http.post(
            `/restful/v1/dd/scarp/importScarpGoods?path=${this.uploadFile.url}&wareHouse=${this.wareHouse}`
          );
          console.log(2)
          if (res.data.code === 1) {
            this.$message.success("操作成功");
            this.uploadFile.url = "";
            this.$router.push({
              path: "/home/storehouse2/scrap",
            });
          } else {
            this.$message.error(res.data.message);
            // this.$refs["upload"].clearFiles();
          }
        } catch (error) {
          // this.$refs["upload"].clearFiles();
          this.$message.error("服务器错误");
        }
      }
    },
    async downloadTemplate () {
    //下载模板
      const { data } = await this.$http.get(
        "/restful/v1/dd/scarp/downloadScarpExcel",
        {
          responseType: "blob",
        }
      );
      try {
        FileSaver.saveAs(
          new Blob([data], { type: "application/octet-stream" }),
          "报废单模板.xls"
        );
      } catch (error) {
        this.$message.error("服务器繁忙")
        console.log(111111, error.message);
      }
    },
    async handleDel() {
      if (this.type === 'edit') {
        const idx = this.selectData.map((el) => el.id);
        for (let i = 0; i < idx.length; i++) {
          const res = await this.$http.post(`/restful/v1/dd/scarp/deletePreserveScarpNumGoods?scarpNum=${this.scarpNum}&goodsId=${this.tableData[idx[i] - i].goodsId01}`)
          if (res.data.code === 1) {
            this.$message.success("删除成功");
          } else {
            this.$message.error(res.data.message)
          }
          this.selectData.splice(idx[i] - i, 1);
          this.tableData.splice(idx[i] - i, 1);
        }
        if (this.tableData.length === 0) {
          this.handleReturn()
        }
        this.fetch()
      } else {
        const idx = this.selectData.map((el) => el.id);
        for (let i = 0; i < this.selectData.length; i++) {
          for (let j = 0; j < idx.length; j++) {
            if (this.selectData[i].id === idx[j]) {
              this.selectData.splice(i, 1);
            }
          }
        }
        for (let i = 0; i < this.tableData.length; i++) {
          for (let j = 0; j < idx.length; j++) {
            if (this.tableData[i].id === idx[j]) {
              this.tableData.splice(i, 1);
            }
          }
        }
      }
    },
    // edit or view
    async fetch() {
      const { data } = await this.$http.post(
        `/restful/v1/dd/scarp/getScarpNumDetail`,
        this.query
      );
      if (data.code === 1 && data.object) {
        this.tableData = data.object.dataList;
        this.total = data.object.dataList.length
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].id = i
        }
        this.$nextTick(function() {
          this.tableData.forEach(item => {
            this.$refs.table.toggleRowSelection(item, true);
          })
        })
      }
    },
    async handleSubmit(status) {
      if (this.tableData.length === 0) {
        return this.$message.info("没有需要提交的信息")
      }
      if (!this.scarpFillTime) {
        return this.$message.info("请填写报废时间");
      }
      let res = null
      if (status) {
        res = await this.$http.post(
          `/restful/v1/dd/scarp/scarpGoodsFilling?status=${status}&scarpTime=${this.scarpFillTime}&scarpNum=${this.scarpNum}`,
          this.tableData
        );
      } else {
        res = await this.$http.post(
          `/restful/v1/dd/scarp/scarpGoodsFilling?status=${status}&scarpTime=${this.scarpFillTime}&scarpNum=${this.scarpNum}`,
          this.selectData
        );
      }
      if (res.data.code === 1) {
        this.$message.success("操作成功");
        this.$router.push({
          path: "/home/storehouse2/scrap",
        });
      } else {
        this.$message.error(res.data.message);
      }
    },
    async handleCheckout(status) {
      if (status === 1) {
        this.$confirm('是否同意审核', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data } = await this.$http.post(
            encodeURI(`/restful/v1/dd/scarp/checkScarpNum?scarpNum=${this.scarpNum}&scarpApplication=${status}&scarpSubReason=${this.textarea}`)
          );
          if (data.code === 1) {
            this.$message.success("操作成功");
            this.$router.go(-1);
            return;
          }
          this.$message.error(data.message);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        });
      } else if (status === 2) {
        if (!this.textarea) {
          return this.$message.info('请填写审核意见')
        }
        this.$confirm('是否不同意审核', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data } = await this.$http.post(
            encodeURI(`/restful/v1/dd/scarp/checkScarpNum?scarpNum=${this.scarpNum}&scarpApplication=${status}&scarpSubReason=${this.textarea}`)
          );
          if (data.code === 1) {
            this.$message.success("操作成功");
            this.$router.go(-1);
            return;
          }
          this.$message.error(data.message);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        });
      }
    },
    handleReturn () {
      this.$router.go(-1);
    },
    async axiosId () {
      const res = await this.$http.post('/restful/v1/dd/inbound/statisticsInboundGoods', this.query1)
      const obj = res.data.object
      for (const key in obj) {
        var arr = key.split('--')
        this.idArr.push(arr[0])
      }
      console.log(this.idArr)
    },
    mouseOver (index) {
      this.active = index
    },
    mouseLeave (index) {
      this.active = null
    },
    async handleSearch (id) {
      this.topForm.goodsId01 = id
      const res = await this.$http.post(
        `/restful/v1/dd/goods/getGoodsInfo?goodsId=${id}&wareHouse=2`
      );
      this.topForm.goodsName = res.data.object.goodsName
      this.topForm.specification = res.data.object.specification
      this.topForm.goodsUnit = res.data.object.goodsUnit
      this.isShow = false
    }
  },
  created() {
    this.type = this.$route.query.type;
    this.query.num = this.$route.query.scarpNum;
    this.scarpNum = this.$route.query.scarpNum;
    this.scarpFillTime = this.$route.query.scarpFillTime;
    console.log(this.$route.query);
    this.checkout = Number(this.$route.query.checkout);
    this.topForm = Object.assign({}, this.initTopForm);
    switch (this.type) {
      case "add": {
        break;
      }
      case "edit":
      case "view": {
        this.fetch();
        break;
      }
    }
  },
  async mounted () {
    const res2 = await this.$http.get(`/restful/v1/dd/permit/getUserDetail?${Math.random()}`);
    this.topForm.scarpPeople = res2.data.object.userName
    this.axiosId()
  },
  computed: {
    newlist () {
      var arr = []
      for (var i = 0; i < this.idArr.length; i++) {
        if (this.idArr[i].indexOf(this.topForm.goodsId01) > -1) {
          arr.push(this.idArr[i])
        }
      }
      return arr
    },
    newlist1() {
      return this.tableData.slice((this.page - 1) * 10, this.page * 10);
    }
  },
  watch: {
    'topForm.goodsId01'() {
      if (this.newlist.length > 0) {
        this.isShow = true
      }
    }
  },
};
</script>
<style lang="less" scoped>
</style>
